package cn.lili.controller.wxpay;


import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.util.Base64;

/**
 * @author User
 */
public class BaseController {
    protected SecretKeySpec secretKeySpec = new SecretKeySpec("qOGaBqCiAn1Qa@Ws".getBytes(), SecurityUtils.AES_KEY_ALGORITHM);

    protected boolean isNotInWechat(HttpServletRequest request) {
        return !isInWechat(request);
    }

    @SuppressWarnings("StringBufferReplaceableByString")
    protected String getBaseUrl(HttpServletRequest request) {
        int port = request.getServerPort();
        StringBuilder defaultDomain = new StringBuilder(request.getScheme());
        defaultDomain.append("://")
                .append(request.getServerName())
                .append(port == 80 ? "" : ":" + port)
                .append(request.getContextPath());
        return defaultDomain.toString();
    }

    protected String base64Encode(String content) {
        return Base64.getEncoder().encodeToString(content.getBytes());
    }

    protected String base64Decode(String content) {
        return new String(Base64.getDecoder().decode(content.getBytes()));
    }

    protected boolean isInWechat(HttpServletRequest request) {
        String ua = request.getHeader("user-agent").toLowerCase();
        return ua.contains("micromessenger");
    }

    protected String encrypt(String content) {
        return AesEncryptUtils.encrypt(content);
    }

    protected String decrypt(String content) {
        return AesEncryptUtils.decrypt(content);
    }

    protected void render(HttpServletResponse response, String content) throws IOException {
        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        out.write(content.getBytes());
        out.flush();
        out.close();
    }
}
